package jpb.module.rest.manager;

import jpb.constant.LogState;
import jpb.constant.Reply;
import jpb.constant.StatusCode;
import jpb.module.daomain.manager.Manager;
import jpb.module.service.manager.ManagerService;
import jpb.security.HandleCookie;
import jpb.security.HandleToken;
import jpb.security.ProduceJwt;
import jpb.util.MD5Coder;
import jpb.util.NetworkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * Created by haol on 2017/3/14.
 */
@RestController
@RequestMapping("/api/web/log")
public class ManagerLoginController {
        @Autowired
        private ManagerService managerService;

        private HandleToken handleToken = new HandleToken();
        private ProduceJwt produceJwt = new ProduceJwt();

        private Logger logger = LoggerFactory.getLogger(ManagerLoginController.class);


        /**
         * @api {POST} /api/web/log/login  登录
         * @apiGroup ManagerLogin
         * @apiName Login
         * @apiDescription 组织管理员登录
         * @apiParam {String} account 账号
         * @apiParam {String} password 密码
         * @apiParamExample {json} 请求样例：
         * POST /api/web/log/login
         * {
         * ""account:"test"
         * "password": "test"
         * }
         * @apiSuccessExample {json} 返回样例:
         * {
         * "code":0,"msg":"登录成功"
         * }
         */

        @RequestMapping(value = "/login", method = RequestMethod.POST)
        public String accountCheck(@RequestParam String account, @RequestParam String password,
                                   HttpServletResponse response, HttpServletRequest request) {
                Manager manager = managerService.getByAccount(account);
                Reply reply = null;
                if (manager != null) {
                        String md5Password = MD5Coder.encodeAccountPwd(account, password);
                        if (manager.getPassword().equals(md5Password)) {

                                long nowMillis = System.currentTimeMillis();
                                Date nowTime = new Date(nowMillis);

                                String subject = handleToken.generalSubject(manager);
                                String jwt = produceJwt.produceWebToken(subject, StatusCode.JWT_ID, StatusCode.JWT_WEB_TTL, nowTime);
                                HandleCookie.saveCookie(response, StatusCode.COOKIE_JWT_WEB, jwt);

                                managerService.updateLoginTime(manager.getId(), nowTime);

                                logger.info("管理员[{}]登录成功,IP地址为[{}]", account, NetworkUtil.getIpAddress(request));
                                reply = new Reply(0, LogState.LOGIN_SUCCESS);
                        } else {
                                logger.info("管理员[{}]登录失败,密码错误", account);
                                HandleCookie.deleteCookie(response, StatusCode.COOKIE_JWT_WEB);
                                reply = new Reply(1, LogState.LOGIN_FAIL);
                        }
                } else {
                        logger.info("用户[{}]登录失败,账号不存在", account);
                        HandleCookie.deleteCookie(response, StatusCode.COOKIE_JWT_WEB);
                        reply = new Reply(1, LogState.LOGIN_FAIL);
                }
                return reply.toJson();
        }

        /**
         * @api {GET} /api/web/log/logout  退出登录
         * @apiGroup ManagerLogin
         * @apiName Logout
         * @apiDescription 组织管理员退出登录
         * @apiSuccessExample {json} 返回样例:
         * {
         * "code":0,"msg":"登出成功"
         * }
         */
        @RequestMapping(value = "/logout", method = RequestMethod.GET)
        public String accountOut(HttpServletResponse response) {
                HandleCookie.deleteCookie(response, StatusCode.COOKIE_JWT_WEB);
                logger.info("用户退出成功");
                return new Reply(1, LogState.LOGOUT_SUCCESS).toJson();
        }

        /**
         *@api {GET} /api/app/log/logState  检查Web登录状态
         * @apiGroup ManagerLogin
         * @apiName checkState
         *  @apiDescription 检测是否登录，未登录则会被拦截，不能到达这里
         *  @apiSuccessExample {json} 返回样例:
         *  {
         *      "true"
         *  }
         */
        @RequestMapping(value = "/logState", method = RequestMethod.GET)
        public boolean check(){
                return true;
        }

}
